package fr.rhoc.android;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import fr.rhoc.android.R;
import fr.rhoc.android.webservices.WebServicesUtils;

public class SendMail extends Activity {

	static final int DIALOG_NO_LIST_DEFINED = 0;
	static final int DIALOG_EMPTY_TEXT = 1;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sendmail);

		final EditText txtMail = (EditText) findViewById(R.id.txt_mail);
		final CheckBox chkChamp = (CheckBox) findViewById(R.id.btn_champ);
		final CheckBox chkLoisirs = (CheckBox) findViewById(R.id.btn_loisirs);
		final ImageButton btnSendMail = (ImageButton) findViewById(R.id.btn_send);

		btnSendMail.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {

				if (!chkChamp.isChecked() && !chkLoisirs.isChecked()) {
					showDialog(DIALOG_NO_LIST_DEFINED);
				} else if ("".equals(txtMail.getText().toString())) {
					showDialog(DIALOG_EMPTY_TEXT);
				} else {
					// Construction url et appel service web
					String url = "";
					url = "http://www.rhoc.fr/webservices/sendmail.php5";
					try {
						List<NameValuePair> postParams = new ArrayList<NameValuePair>(
								3);
						postParams.add(new BasicNameValuePair("champ", chkChamp
								.isChecked() ? "1" : "0"));
						postParams.add(new BasicNameValuePair("loisirs",
								chkLoisirs.isChecked() ? "1" : "0"));
						postParams.add(new BasicNameValuePair("mail", txtMail
								.getText().toString()));
						WebServicesUtils.callService(url, postParams);
					} catch (IOException e) {
						Log.e("log_tag",
								"I/O Error getting WS answer " + e.toString());
					}

				}

			}
		});

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
		AlertDialog.Builder builder;
		switch (id) {
		case DIALOG_NO_LIST_DEFINED:
			builder = new AlertDialog.Builder(this);
			builder.setMessage("Choisir une liste de destinataires");
			builder.setTitle("Envoi impossible");
			builder.setPositiveButton("OK", null);
			dialog = builder.create();
			break;
		case DIALOG_EMPTY_TEXT:
			builder = new AlertDialog.Builder(this);
			builder.setMessage("Le texte du mail est vide !");
			builder.setTitle("Envoi impossible");
			builder.setPositiveButton("OK", null);
			dialog = builder.create();
			break;
		default:
			dialog = null;
		}
		return dialog;
	}

}
